<!-- 科研人员 -->
<template>
  <div class="module_">
    <div class="mb8">
      <search @clearSearch='clearSearch' :status='true'>
        <el-form label-width='80px' inline autocomplete="off" :model="pageparm" class="search_box">
          <el-form-item label="科室" v-if="adminShow">
            <inputSearch ref="d_Search" type="departments" @onChange='s_chage($event,"belong_department_id")' />
          </el-form-item>
          <el-form-item label="姓名">
            <inputSearch :options="{review_status:null}" ref="e_Search" @onChange='s_chage($event,"employees_id")' />
          </el-form-item>
          <el-form-item label="工号">
            <el-input clearable size="medium" v-model="pageparm.code" placeholder="请输入工号搜索"></el-input>
          </el-form-item>
          <el-form-item label="系统角色">
            <el-select size="medium" v-model="pageparm.roles_id" clearable placeholder="请选择系统角色"
              @change="s_chage($event,'roles_id')">
              <el-option v-for="(item) in roleList" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="科研专员">
            <el-select size="medium" v-model="pageparm.is_research" clearable placeholder="请选择是否为科研专员"
              @change="s_chage($event,'is_research')">
              <el-option v-for="(item) in researchList" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="审核状态">
            <el-select size="medium" v-model="pageparm.review_status" clearable placeholder="请选择审核状态"
              @change="s_chage($event,'review_status')">
              <el-option v-for="(item) in reviewStatusList" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <template slot="footer">
          <el-button v-permission="{action:'科研人员添加',effect:'delete'}" size="medium" type="primary"
            @click="handle(null,{is_research:0},3)">新建员工</el-button>
          <el-popover
            v-permission="{action:'人员转岗',effect:'delete'}"
            class="ml8"
            placement="bottom"
            v-model="transferObj.transfer"
            trigger="manual">
            <div class="mb16">
              <inputSearch ref="e_search" :options="{type:'other_department'}" @onChange='nameChange' />
            </div>
            <div class="tx-r">
              <el-button size="medium" @click="cancel">取消</el-button>
              <el-button size="medium" type="primary" @click.stop="submitTransfer" :loading='transferObj.transfer_loading'>确定</el-button>
            </div>
            <el-button slot="reference" plain size="medium" @click="transferObj.transfer = true">人员转入</el-button>
          </el-popover>
          <exportExcel :apiFn='Apiemployees' name='科研人员' :self='true' :dataFn='dataFn' />
        </template>
      </search>
    </div>
    <el-table id="out-table" ref="table" :data="tableData" class="flex-1" height="100%" size="medium" border
      highlight-current-row v-loading="tableLoading" @sort-change="tableSortChange" :row-class-name="tableRowClassName">
      <el-table-column align="center" v-for="(item,i) in headerList" :key="item.prop" :prop="item.prop"
        :label="item.label" :min-width="item.width" :fixed="i === 0 ? true: false" show-overflow-tooltip
        :sortable="item.noSortable ? false:'custom'">
        <template slot-scope="scope">
          <template v-if="item.exportName">
            {{echoExportName(scope.row,item.exportName)}}
          </template>
          <template v-else-if="item.prop === 'review_status'">
            <span v-if="scope.row.review_status === 2"
              class="c-red">{{newReviewStatusObj[scope.row.review_status]}}：{{scope.row.review_comment}}</span>
            <span v-else>{{newReviewStatusObj[scope.row.review_status]}}</span>
          </template>
          <template v-else-if="item.prop === 'roles_id'">
            {{scope.row.role?scope.row.role.name:''}}
          </template>
          <template v-else-if="item.prop === 'gander'">
            {{scope.row.gander === 1 ? '男':'女'}}
          </template>
          <template v-else-if="item.prop === 'is_research'">
            {{scope.row.is_research === 1 ? '是':'否'}}
          </template>
          <template v-else-if="item.prop === 'first_education'">
            {{echo(scope.row.first_education,firstEducation)}}
          </template>
          <template v-else-if="item.prop === 'professional_rank_level'">
            {{echo(scope.row.professional_rank_level,professionalRankLevel)}}
          </template>
          <template v-else>
            {{ scope.row[item.prop] }}
          </template>
        </template>
      </el-table-column>
      <el-table-column fixed="right" align="center" label="操作" width="200" class-name="operation">
        <div class="flex-justify-end" slot-scope="scope">
          <el-tooltip effect="dark" content="审核" placement="bottom-end" v-show="scope.row.review_status == 0 || scope.row.review_status == 4">
            <el-button v-permission="{action:'科研人员审核',effect:'delete'}" type="primary"
              @click="examine_btns(scope.row,1)" size="small" icon="el-icon-help" circle></el-button>
          </el-tooltip>
          <el-tooltip effect="dark" content="人员详情" placement="bottom-end">
            <el-button size="small" type="info" @click="goDetail(scope.row)" icon="el-icon-more" circle></el-button>
          </el-tooltip>
          <el-tooltip effect="dark" content="修改信息" placement="bottom-end">
            <el-button size="small" v-permission="{action:'科研人员编辑',effect:'delete'}"
              @click="handle(scope.$index, scope.row,2)" icon="el-icon-edit" circle></el-button>
          </el-tooltip>
          <el-tooltip v-if="delInfo(scope.row)" effect="dark" content="删除" placement="bottom-end">
            <el-button size="small" v-permission="{action:'科研人员删除',effect:'delete'}" type="danger"
              @click="deleteUser(scope.$index, scope.row)" icon="el-icon-delete" circle></el-button>
          </el-tooltip>
          <el-tooltip effect="dark" content="重置密码" placement="bottom-end">
            <el-button size="small" v-permission="{action:'重置密码',effect:'delete'}" type="warning"
              @click="changePassword(scope.row)" icon="el-icon-refresh" circle></el-button>
          </el-tooltip>
        </div>
      </el-table-column>
    </el-table>

    <Pagination v-bind:child-msg="pageparm" @callFather="callFather"></Pagination>

    <el-dialog :visible.sync="editFormVisible" width="700px" @click="editFormVisible = false" @closed="btnLoading = false"
      @close='dialogClose' :close-on-click-modal='false' :close-on-press-escape='false'>
      <h2 slot="title" class="tx-c fb">{{dialogTitle}}</h2>
      <el-form autocomplete="off" label-width="100px" :model="editForm" class="form_flex">
        <el-form-item v-for="(v, i) in editHeaderList" :key="i" :label="v.label" :class="v.required ? 'tip' : ''">
          <inputSearch ref="departmentSearch" type="departments" @onChange='searchChange($event,"belong_department_id")'
            :departmentsId='departmentsId' v-if="v.prop === 'belong_department_id'" />
          <el-select clearable v-else-if="v.prop === 'roles_id'" size="medium" v-model="editForm[v.prop]"
            placeholder="请选择职务">
            <el-option v-for="(item) in roleListFilter()" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
          <el-input v-else-if="v.prop === 'employees_id'" size="medium" type="text" clearable v-model="editForm.name"
            placeholder="请输入姓名" />
          <el-radio-group v-else-if="v.prop === 'gander'" v-model="editForm[v.prop]">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
          </el-radio-group>
          <el-radio-group v-else-if="v.prop === 'is_research'" v-model="editForm[v.prop]">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
          <el-select clearable v-else-if="v.prop === 'first_education'" size="medium" v-model="editForm[v.prop]"
            placeholder="请选择最高学历">
            <el-option v-for="(item,index) in firstEducation" :key="index" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
          <el-select clearable v-else-if="v.prop === 'professional_rank_level'" size="medium" v-model="editForm[v.prop]"
            placeholder="请选择职称级别">
            <el-option v-for="(item,index) in professionalRankLevel" :key="index" :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
          <el-input v-else size="medium" :type="v.type" autosize clearable v-model="editForm[v.prop]"
            @mousewheel.native.prevent
            :placeholder="'请输入' + v.label" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="flex-justify-bcenter">
        <el-button @click="editFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit" :loading='btnLoading'>确 定</el-button>
      </div>
    </el-dialog>


    <!-- <el-dialog v-if="editPassword" :visible.sync="editPassword" width="500px" @click="editPassword = false"
      :close-on-click-modal='false' :close-on-press-escape='false'>
      <h2 slot="title" class="tx-c fb">重置密码</h2>
      <password  :code='changeCode' :editPassword.sync="editPassword" />
    </el-dialog> -->

    <!-- 审核 -->
    <examine ref="examine" @submit='(options)=>examineSubmit(options,1)' />

    <!-- 变更审核 -->
    <examine ref="examineChange" @submit='(options)=>examineSubmit(options,2)' title="转岗审核" >  
      <el-form label-width="80px">
        <el-form-item label="原科室">
          <p class="f-16 fb">{{examineChangeObj.old_department_name}}</p>
        </el-form-item>
        <el-form-item label="变更科室">
          <p class="f-16 fb">{{examineChangeObj.new_department_name}}</p>
        </el-form-item>
      </el-form>
    </examine>
  </div>
</template>

<script>
  import {
    Apiemployees,
    ApiemployeesAdd,
    ApiemployeesPut,
    ApiemployeesDel,
    ApiemployeesCheck,
    Apiroles,
    ApipasswordReset,
    ApichangeDepartment,
    ApichangeDepartmentInfo,
    ApichangeDepartmentPut
  } from '@/api'
  import {
    firstEducation,
    firstEducationObj,
    professionalRankLevel,
    professionalRankLevelObj,
    reviewStatus,
    reviewStatusObj
  } from '@/assets/js'
  import {debounce,adminShow} from "@/utils/index";
  import {headerList,researchList} from '../js/researchers'
  import password from "../components/password.vue"
  import {isPhone} from "@/utils/test"
  let refresh = true
  export default {
    name: 'researchers',
    beforeRouteEnter(to, from, next) {
      if (from.name === "ranks_researchers_detail") {
        refresh = false
      } else {
        refresh = true
      }
      next()
    },
    components:{
      password
    },
    computed: {
      reviewStatusList(){
        return [...reviewStatus,{label: "转岗未审核",value: 4}]
      },
      newReviewStatusObj(){
        return {...reviewStatusObj,4:"转岗未审核"}
      },
      editHeaderList() {
        return headerList.filter(item => item.prop !== 'review_status')
      }
    },
    data() {
      return {
        Apiemployees,
        adminShow: adminShow(),
        tableData: [],
        editFormVisible: false,
        editForm: {}, //修改或者查看详情

        pageparm: {
          page: 1,
          perPage: 20,
          total: null,
          sort_str: null,
          sort_order: 'desc',
          code: null,
          belong_department_id: null,
          employees_id: null,
        },
        tableLoading: false,

        bindRoles: false, //绑定角色
        bindRolesObj: {
          employees_id: null,
          employees_name: null,
          roles_id: null
        },
        btnLoading: false,

        headerList,
        firstEducation,
        professionalRankLevel,
        // reviewStatus,
        // reviewStatusObj,
        departmentsId: null,
        rules: ['name', 'code', 'belong_department_id', 'gander', 'roles_id'],

        examine_id: null, //审核id
        roleList: [],
        researchList,
        dialogTitle: '',
        // editPassword: false,
        // changeCode:''
        transferObj:{   //转岗申请
          transfer: false,
          transfer_id: null,
          transfer_loading: false
        },
        examineChangeObj:{
          old_department_name:"",
          new_department_name:"",
        }
      }
    },
    activated() {
      if (refresh) {
        this.pageparm.page = 1
      }
      this.getList()
      setTimeout(() => {
        Apiroles({allPage: 2}).then(({
          data
        }) => {
          this.roleList = data
        })
      }, 100)
    },
    deactivated(){
      this.transferObj.transfer = false
    },
    methods: {
      submitTransfer(){
        if(!this.transferObj.transfer_id){
          this.$message.error('请先选择转岗人员')
          return
        }
        this.transferObj.transfer_loading = true
        ApichangeDepartment({employee_id:this.transferObj.transfer_id}).then(res=>{
          this.$message.success('转岗申请已提交管理员审核！')
          this.cancel()
        }).finally(()=>{
          this.transferObj.transfer_loading = false
        })
      },
      cancel(){
        this.$refs.e_search.clear()
        this.transferObj.transfer = false
        this.transferObj.transfer_id = null
      },
      nameChange(id){
        this.transferObj.transfer_id = id
      },
      changePassword(item){
        // this.changeCode = item.employee.code
        // this.editPassword = true
        this.$confirm(`此操作将重置 <span class="c-red">${item.employee.name}</span> 该职员登录密码, 是否继续?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          dangerouslyUseHTMLString: true,
        }).then(_=>{
          const loading = this.$loading({
            lock: true,
            text: '重置中...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          const newPassword = {employee_code:item.employee.code,new_password:'123456',new_password_confirmation:'123456'}
          ApipasswordReset(newPassword).then(res => {
            this.$message.success('重置成功！重置后的密码为123456');
          }).finally(()=>{
            loading.close()
          })
        }).catch(_=>{})
      },
      tableRowClassName({row, rowIndex}) {
        if (row.employees_id === this.$store.state.userInfo.employees_id) {
          return 'warning-row';
        } else if (rowIndex % 2 === 0) {
          return 'success-row';
        }
        return '';
      },
      roleListFilter() {
        return this.roleList.filter(item => item.id >= this.$store.state.userInfo.role_id)
      },
      echoExportName(val, name) {
        const [a, b] = name.split('.')
        return val[a] ? val[a][b] : ''
      },
      delInfo(info) {
        if(!info.delete){
          return false
        }else if(this.$store.state.userInfo.employees_id === info.employees_id){
          return false
        }else{
          return true
        }
      },
      dataFn(data, tableHeade) {
        let tabStr = ''
        data.forEach((item, index) => {
          let tabRowStr = "";
          tabStr += `<tr>`;
          for (let i = 0; i < tableHeade.length; i++) {
            const key = tableHeade[i]
            if (/\./g.test(key)) {
              let arr = key.split('.')
              tabRowStr += `<td>${item[arr[0]] ? item[arr[0]][arr[1]] : ''}</td>`;
            } else if (key === 'review_status') {
              tabRowStr += `<td>${this.newReviewStatusObj[item.review_status]}</td>`;
            } else if (key === 'roles_id') {
              tabRowStr += `<td>${item.role ? item.role.name : '' }</td>`;
            } else if (key === 'gander') {
              tabRowStr += `<td>${item.gander === 1 ? '男':'女'}</td>`;
            }else if (key === 'is_research') {
              tabRowStr += `<td>${item.is_research === 1 ? '是':'否'}</td>`;
            } else if (key === 'first_education') {
              tabRowStr += `<td>${firstEducationObj[item.first_education] || ""}</td>`;
            } else if (key === 'professional_rank_level') {
              tabRowStr += `<td>${professionalRankLevelObj[item.professional_rank_level] || ''}</td>`;
            } else {
              tabRowStr += `<td>${item[key] || ''}</td>`;
            }
          }
          tabStr += tabRowStr;
          tabStr += "</tr>";
        });
        return tabStr
      },
      // 详情
      goDetail(item) {
        this.$router.push('/ranks/researchers_detail?id=' + item.employees_id)
      },
      //审核
      examineSubmit(options,i) {
        const loading = this.$loading({
          lock: true,
          text: '加载中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        options.id = this.examine_id
        const api = i == 1 ? ApiemployeesCheck : ApichangeDepartmentPut
        api(options, options.id).then(res => {
          this.getList()
        }).catch(() => {
          this.$message.error('服务器错误，请重新提交');
        }).finally(() => {
          loading.close()
        })
      },
      examine_btns(item, i) {
        this.examine_id = item.employees_id
        if(item.review_status == 0){
          this.$refs.examine.examineShow = true
        }else if(item.review_status == 4){
          this.$refs.examineChange.examineShow = true
          ApichangeDepartmentInfo(this.examine_id).then(res => {
            this.examineChangeObj = res.data
          })
        }
      },
      echo(i, arr) {
        let label
        for (const item of arr) {
          if (item.value === i) {
            label = item.label
            break;
          }
        }
        return label
      },
      tableSortChange(column) {
        if (column.order === "descending") {
          this.pageparm.sort_str = column.prop;
          this.pageparm.sort_order = "desc";
        } else if (column.order === "ascending") {
          this.pageparm.sort_str = column.prop;
          this.pageparm.sort_order = "asc";
        } else {
          this.pageparm.sort_str = null;
          this.pageparm.sort_order = null;
        }
        this.getList()
      },
      //搜索
      clearSearch() {
        this.$refs.e_Search.clear()
        if (this.adminShow) this.$refs.d_Search.clear()
      },
      s_chage(id, val) {
        this.pageparm[val] = id
        this.pageparm.page = 1
        this.getList()
      },
      //分页
      callFather(pageparm) {
        this.pageparm.page = pageparm.page
        this.pageparm.perPage = pageparm.perPage
        this.getList()
      },
      getList() {
        this.tableLoading = true
        Apiemployees(this.pageparm).then(({data,page}) => {
          this.tableData = data || []
          this.pageparm.total = page.total
          this.tableLoading = false
        }).catch(() => {
          this.tableLoading = false
        })
      },
      handle(index, value, i) {
        this.editForm = {...value}
        this.editFormVisible = true
        this.dialogTitle = '新建员工'
        if (i == 2) {
          this.dialogTitle = '修改员工'
          this.$set(this.editForm, 'name', value.employee.name)
          this.$set(this.editForm, 'code', value.employee.code)
          this.$nextTick(() => {
            this.$refs.departmentSearch[0].departments_id = value.belong_department_id
          })
        } else {
          if (!this.adminShow) {
            this.editForm.belong_department_id = this.$store.state.userInfo.department_id
            this.$nextTick(() => {
              this.$refs.departmentSearch[0].departments_id = this.editForm.belong_department_id
            })
          }
        }
      },
      departmentsChange(id) {
        this.editForm.belong_department_id = id
      },
      searchChange(id, val) {
        this.editForm[val] = id
      },
      dialogClose() {
        this.$refs.departmentSearch[0].clear()
      },
      deleteUser(index, value) {
        this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const loading = this.$loading({
            lock: true,
            text: '加载中...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          ApiemployeesDel(value.employees_id).then(res => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.getList()
          }).finally(() => {
            loading.close()
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      submit: debounce(function () { //提交  修改或新增
        const options = {
          ...this.editForm
        }
        // options.coefficient = this.editForm.coefficient || 1
        for (const key of this.rules) {
          if (!options[key] && options[key] !== 0) {
            this.$message({
              type: 'error',
              message: '必填信息请填写完整！'
            });
            return
          }
        }
        if(options.phone && !isPhone(options.phone)){
          this.$message.error('请输入正确电话');
          return
        }
        this.btnLoading = true
        if (options.employees_id) { //有ID就是修改
          ApiemployeesPut(options, options.employees_id).then(res => {
            this.$message({
              type: 'success',
              message: '修改成功!'
            });
            this.editFormVisible = false
            this.getList()
          }).catch(() => {
            this.btnLoading = false
            this.$message({
              type: 'error',
              message: '修改失败!'
            });
          })
        } else {
          ApiemployeesAdd(options).then(res => {
            this.$message({
              type: 'success',
              message: '添加成功!'
            });
            this.editFormVisible = false
            this.getList()
          }).catch(() => {
            this.$message({
              type: 'error',
              message: '添加失败!'
            });
            this.btnLoading = false
          })
        }
      }, 800, true)
    },

  }
</script>
<style lang='less' scoped>
  .form_flex {
    /deep/.el-form-item__content {
      width: 220px;
    }
  }
  /deep/.el-table .warning-row {
    background: oldlace;
  }

  /deep/.el-table .success-row {
    background: #FAFAFA;
  }
</style>